<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域  -->
    <el-card>
      <!-- 提示框 -->
      <el-alert title="消息提示的文案" type="info" center show-icon> </el-alert>
      <!-- activeIndex的值必须是一个数字 可以通过-0操作隐式转换 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- form表单 -->
      <el-form
        :model="addform"
        label-width="100px"
        label-position="top"
        :rules="addFormRules"
        ref="addformRef"
      >
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addform.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price" type="number"
              ><el-input v-model="addform.goods_price"></el-input
            ></el-form-item>
            <el-form-item label="商品重量" prop="goods_weight" type="number"
              ><el-input v-model="addform.goods_weight"></el-input
            ></el-form-item>
            <el-form-item label="商品数量" prop="goods_number" type="number"
              ><el-input v-model="addform.goods_number"></el-input
            ></el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addform.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader
            ></el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTabDate"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cd"
                  v-for="(cd, i) in item.attr_vals"
                  :key="i"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTabDate"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3"
            ><el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload></el-tab-pane
          >
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addform.goods_introduce"></quill-editor>
            <!-- 添加商品的按钮   -->
            <el-button type="primary" class="btnAdd" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <div style="background: red" width="50px" height="50px"></div>
      <img :src="previewPath" alt="" class="previewclass" />
    </el-dialog>
  </div>
</template>
<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'
export default {
  components: {
    quillEditor,
  },
  data() {
    return {
      // 存储预览路径
      previewPath: '',
      // 预览对话框显示标记
      previewVisible: false,
      // 设置请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token'),
      },
      // 上传图片的url地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 静态属性列表
      onlyTabDate: [],
      // 动态参数列表
      manyTabDate: [],
      cateList: [],
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
      },
      addform: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品分类数组
        goods_cat: [],
        // 存放图片的数组
        pics: [],
        goods_introduce: '',
        attrs: [],
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' },
        ],
      },
      // 当前触发高亮显示的索引
      activeIndex: '0',
    }
  },
  created() {
    this.getcatelist()
  },
  methods: {
    async getcatelist() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      }
      this.cateList = res.data
      // console.log(this.cateList)
    }, // 级联样式选择器触发事件
    handleChange() {
      // console.log(this.addform.goods_cat)
      //   只允许选择三级组件
      if (this.addform.goods_cat.length !== 3) {
        this.addform.goods_cat = []
      }
    }, // 切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。
    beforeTabLeave(activeName, oldActiveName) {
      //   console.log(activeName)
      //   console.log(oldActiveName)
      if (oldActiveName === '0' && this.addform.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
    }, // tab 被选中时触发
    async tabClicked() {
      //   console.log(this.activeIndex)
      // 证明tab选择切换到动态参数操作
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'many' },
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取动态列表参数失败')
        }
        // 循环attr_vals需要将服务器返回的字符串转新的数组
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
        })
        this.manyTabDate = res.data
        // console.log(this.manyTabDate)
      } // 证明tab选择切换到静态属性操作
      if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' },
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('获取静态属性列表失败')
        }
        // // 循环attr_vals需要将服务器返回的字符串转新的数组
        // res.data.forEach((item) => {
        //   item.attr_vals =
        //     item.attr_vals.length === 0 ? [] : item.attr_vals.split(',')
        // })
        this.onlyTabDate = res.data
        // console.log(this.onlyTabDate)
      }
    }, // 图片移除事件
    handleRemove(file) {
      // console.log(file)
      // 找到图片的临时存储路径
      const filePath = file.response.data.tmp_path
      // 从pics中找到删除图片的索引
      const i = this.addform.pics.findIndex((x) => x.pic === filePath)
      this.addform.pics.splice(i, 1)
      // console.log(this.addform)
    }, // 图片预览事件
    handlePreview(file) {
      // console.log(file)
      this.previewPath = file.response.data.url
      // console.log(this.previewPath)
      this.previewVisible = true
    }, // 图片成功上传事件
    handleSuccess(response) {
      // console.log(response)
      // 拼接一个图片信息对象
      const picInfo = { pic: response.data.tmp_path }
      this.addform.pics.push(picInfo)
      // console.log(this.addform)
    }, // 添加商品事件
    add() {
      // 表单预验证
      this.$refs.addformRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项')
        }
        // 验证通过执行业务逻辑
        // 将goods_cat转换为以逗号切割的字符串 可能会报错，因为级联样式表所需要的是一个数组
        // 但是post中参数要求字符串格式，可以安装一个深拷贝的依赖包，声明一个常量来接受深拷贝的结果，
        // 改变这个对象中的goods_cat，将这个常量传递给参数使用
        this.addform.goods_cat = this.addform.goods_cat.join(',')
        // 处理动态参数
        this.manyTabDate.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals.join(','),
          }
          this.addform.attrs.push(newInfo)
        })
        // 处理静态参数
        this.onlyTabDate.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_vals: item.attr_vals,
          }
          this.addform.attrs.push(newInfo)
        })
        // console.log(this.addform)
        const { data: res } = await this.$http.post('goods', this.addform)
        if (res.meta.status !== 201) {
          return this.$message.error('创建商品失败')
        }
        this.$message.success('创建商品成功！')
        this.$router.push('/goods')
      })
    },
  },
  computed: {
    cateId() {
      if (this.addform.goods_cat.length === 3) {
        return this.addform.goods_cat[2]
      }
      return null
    },
  },
}
</script>
<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewclass {
  width: 100%;
}
.btnAdd {
  margin-top: 15px;
}
</style>
